
/**
 * Date:2019年5月31日下午3:00:50
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.common.coder;

import java.io.IOException;

import org.jboss.marshalling.Marshaller;

import io.netty.buffer.ByteBuf;

/**
 * Description: TODO <br/>
 * Date: 2019年5月31日 下午3:00:50 <br/>
 * 
 * @author xuejianxin
 */
public class MyMarshallingEncoder {
	private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
	private final Marshaller marshaller;

	public MyMarshallingEncoder() throws IOException {
		this.marshaller = MarshallingCodeCFactory.buildMarshalling();
	}

	public void encode(Object msg, ByteBuf out) throws Exception {
		try {
			int lengthPos = out.writerIndex();
			out.writeBytes(LENGTH_PLACEHOLDER);
			MyChannelBufferByteOutput output = new MyChannelBufferByteOutput(out);
			marshaller.start(output);
			marshaller.writeObject(msg);
			marshaller.finish();
			out.setInt(lengthPos, out.writerIndex() - lengthPos - 4);
		} finally {
			this.marshaller.close();
		}
	}

}
